package client.comm.baoding.ui.vm

import android.app.Application
import android.net.Uri
import android.text.TextUtils
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.comm.baoding.api.bean.RealRet
import client.comm.baoding.api.bean.UploadRet
import client.comm.commlib.network.data.JsonResult
import client.comm.commlib.network.data.Ret
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.Util
import client.comm.baoding.ui.viewmodel.MiddleVm
import client.comm.commlib.out_time
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Response

class RegisterViewModel(app: Application) : MiddleVm(app) {

    val accountReg = MutableLiveData<String>("")
    val username = MutableLiveData<String>("")
    val passwordReg = MutableLiveData<String>("")
    val passwordAgainReg = MutableLiveData<String>("")
    val invate = MutableLiveData<String>("")
    val smscode = MutableLiveData<String>("")
    val isShowing = MutableLiveData<Boolean>()

    val isShowPwdReg = MutableLiveData<Boolean>(false)
    val isShowPwdAgainReg = MutableLiveData<Boolean>(false)
    val getCodeEnable = MutableLiveData<Boolean>(true)
    val tyType = MutableLiveData<Int>(-1)
    val getCodeTxt = MutableLiveData<String>("获取验证码")
    val registerRet = MutableLiveData<JsonResult<Ret>>()
    val codeRet = MutableLiveData<JsonResult<Ret>>()

    val realNameVerifyRet = MutableLiveData<JsonResult<RealRet>>()

    //实名认证字段
    val realname = MutableLiveData<String>("")
    val idcard = MutableLiveData<String>("")
    val imgOne = MutableLiveData<Uri>(null)


    fun switchTy() {
        if (tyType.value != 1) {
            tyType.value = 1
        } else {
            tyType.value = -11

        }
    }

    fun switchIsShowPwdReg() {
        isShowPwdReg.value = !isShowPwdReg.value!!
    }

    fun switchIsShowAgainPwdReg() {
        isShowPwdAgainReg.value = !isShowPwdAgainReg.value!!
    }


    /**
     * 注册
     */
    fun register() {
//        if (tyType.value != 1) {
//            toast("请同意用户协议")
//            return
//        }

        if (TextUtils.isEmpty(accountReg.value)
            || TextUtils.isEmpty(smscode.value)
            || TextUtils.isEmpty(username.value)
            || TextUtils.isEmpty(invate.value)
            || TextUtils.isEmpty(passwordAgainReg.value)
            || TextUtils.isEmpty(passwordReg.value)
        ) {
            toast("所有不能为空")
            return
        }

        if (!passwordReg.value.equals(passwordAgainReg.value)) {
            toast("两次密码输入不一致")
            return
        }

        isShowing.value = true
        hold({
            server.register(
                username.value!!,
                accountReg.value!!,
                passwordReg.value!!,
                passwordAgainReg.value!!,
                smscode.value!!,
                invate.value!!
            )
        }, {
            registerRet.value = null
        }, {
            registerRet.value = it
        }, complete = {
            isShowing.value = false
        })

    }

    fun getCode() {

        if (TextUtils.isEmpty(accountReg.value)) {
            toast("手机号不能为空")
            return
        }

        isShowing.value = true
        hold({
            val ts = System.currentTimeMillis()
            server.getcode(
                accountReg.value!!,
                "${ts}",
                Util.getCaptchaSign(accountReg.value!!, "${ts}")
            )
        }, {
            getCodeEnable.value = false
            codeRet.value = null
        }, {
            codeRet.value = it
        }, complete = {
            isShowing.value = false
        }, err = {
            getCodeEnable.value = true
        })

    }

    fun realnameEnter() {

        if (TextUtils.isEmpty(realname.value)
            || TextUtils.isEmpty(idcard.value)
        ) {
            toast("所有不能为空")
            return
        }

        hold({
            server.user_real_name(
                realname.value!!.trim(),
                idcard.value!!.trim(),
                "",
            )
        }, {
            isShowing.value = true
        }, {
            realNameVerifyRet.value = it
        }, complete = {
            isShowing.value = false
        })

    }

//    fun realnameEnter(owner: LifecycleOwner) {
//        if (TextUtils.isEmpty(realname.value)
//            || TextUtils.isEmpty(idcard.value)
//            || imgOne.value == null
//        ) {
//            toast("所有不能为空")
//            return
//        }
//        isShowing.value = true
//        //上传图片
//        viewModelScope.launch {
//            flow {
//
//                var emm: Response<JsonResult<UploadRet>>? = null
//                val file = Util.getLuBan(
//                    owner,
//                    imgOne.value!!
//                )
//                val requestFile: RequestBody = RequestBody.create(
//                    "multipart/form-data".toMediaTypeOrNull(),
//                    file
//                )
//                val body = MultipartBody.Part.createFormData(
//                    "file",
//                    file.name,
//                    requestFile
//                )
//                val descriptionString = "file"
//                val description = RequestBody.create(
//                    "multipart/form-data".toMediaTypeOrNull(),
//                    descriptionString
//                )
//                out_time {
//                    val ret = server.upload(description, body)
//                    emm = ret
//                }
//
//                emit(emm)
//            }.map {
//                var emm: JsonResult<Ret>? = null
//
//                it?.body()?.let {
//                    if (it.isSuccess) {
//                        out_time {
//                            val ret = server.user_real_name(
//                                realname.value!!,
//                                idcard.value!!,
//                                it.data!!.url,
//                            )
//                            emm = ret?.body()
//                        }
//                    } else {
//                        emm = JsonResult<Ret>().apply {
//                            message = it.message
//                        }
//                    }
//                }
//                emm
//            }.flowOn(Dispatchers.IO).onCompletion { cause ->
//                isShowing.value = false
//            }.catch { cause ->
//                if (cause != null) {
//                    toast(cause.message)
//                }
//            }.collectLatest {
//                realNameVerifyRet.value = it
//            }
//        }
//
//    }


}